package com.zhiyou100.util.json;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;

/**
 * @author yang
 * @packageName FastJsonTools
 * @className com.zhiyou100.tools
 * @Description TODO FastJson 工具类
 * @date 7/27/20
 */
public class FastJsonTools {
    /**
     * @return java.lang.String
     * @Description TODO 自定义时间格式
     * @name toJson
     * @param: [object, dateFormat]
     * @date 7/27/20 15:32
     * @author yang
     */
    public static String objectToJson(Object object, String dateFormat) {
        JSONObject.DEFFAULT_DATE_FORMAT = dateFormat;
        //设置日期格式
        return JSONObject.toJSONString(object, SerializerFeature.WriteDateUseDateFormat);
    }

    /**
     * @return java.lang.String
     * @Description TODO 默认时间格式  yyyy-MM-dd"
     * @name toJson
     * @param: [object]
     * @date 7/27/20 15:32
     * @author yang
     */
    public static String objectToJson(Object object) {
        return objectToJson(object, "yyyy-MM-dd");
    }


    /**
     * @return com.alibaba.fastjson.JSONObject
     * @Description TODO 获取请求内容转为一个 json 对象
     * @name receivePost
     * @param: [request]
     * @date 7/28/20 21:57
     * @author yang
     */
    public static JSONObject receivePost(HttpServletRequest request) throws IOException {

        // 读取请求内容
        BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), StandardCharsets.UTF_8));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        //将json字符串转换为json对象
        return JSONObject.parseObject(sb.toString());
    }


    public static void main(String[] args) {

        JSONObject zhangsan = new JSONObject();

        zhangsan.put("birthday", new Date());

        System.out.println(JSONObject.toJSONString(zhangsan));
        // {"birthday":1595835286356}

        String s = objectToJson(zhangsan);
        System.out.println(s);
        // {"birthday":"2020-07-27"}


        ArrayList<Integer> integers = new ArrayList<>();
        integers.add(1);
        integers.add(2);
        System.out.println(objectToJson(integers));

    }
}
